//
//  SVProgressHUDAddStyle.m
//  SVProgreCMCCIOTtudy
//
//  Created by s on 16/5/30.
//  Copyright © 2016年 s. All rights reserved.
//

#import "SVProgressHUDSub.h"

#define   hudViewleftEdge  25.0   //hudView 距离父视图左边的距离
#define   hudViewWide   [UIScreen  mainScreen].bounds.size.width-2*hudViewleftEdge  //hudView 宽度
#define   indefiniteViewLeftEdge 5.0     // 转圈距离父视图左边的距离
#define   indefiniteViewWidth  48  // 当有字体显示的时候，默认菊花圈的宽度
#define   statusTextLableTopEdge 10.0  // 标签距离顶部的距离


typedef NS_ENUM(NSInteger, PROGRESS_TYPE) {
    PROGRESS_TYPE_IOS,
    PROGRESS_TYPE_ANDROID
};


@interface SVProgressHUDSub()

@property (nonatomic, readwrite) CGFloat progress;
@property(nonatomic,assign)PROGRESS_TYPE progressType;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, strong) UIView *hudView;
@property (nonatomic, strong) UIView *indefiniteAnimatedView;
@property (nonatomic, strong) SVProgressAnimatedView *ringView;
@property (nonatomic, strong) SVProgressAnimatedView *backgroundRingView;
@property (nonatomic, readwrite) NSUInteger activityCountRequest;
@property (nonatomic, assign) BOOL  isFinishActivity;
@property (nonatomic, assign) BOOL  isWaitFinish;
@property (nonatomic, assign) BOOL  isStartActivity;
@property (nonatomic, assign) double  currentDelay;
@property (nonatomic, assign) float  undefinedProgress;

@property (nonatomic, strong) UIControl *overlayView;


@end


@implementation SVProgressHUDSub{

  BOOL _isInitializing;
}

+ (SVProgressHUD*)sharedView {
    static dispatch_once_t once;
    
    static SVProgressHUD *sharedView;
#if !defined(SV_APP_EXTENSIONS)
    dispatch_once(&once, ^{ sharedView = [[self alloc] initWithFrame:[[[UIApplication sharedApplication] delegate] window].bounds]; });
#else
    dispatch_once(&once, ^{ sharedView = [[self alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; });
#endif
    return sharedView;
    
    
}
#pragma mark - Instance Methods
+(void)showProgress:(float)progress status:(NSString*)status {
    SVProgressHUDSub  *shareView=(SVProgressHUDSub  *)[self sharedView];
    //        注册通知
    [[NSNotificationCenter  defaultCenter] addObserver:shareView selector:@selector(closeAfterShowProgress) name:SVProgressHUDDidAppearNotification object:nil];
    shareView.undefinedProgress=progress;
    shareView.statusLabel.text = status;
    if (progress==SVProgressHUDUndefinedProgress) {
    // 如果取消事件已经完成 开始菊花会使activityCount 加1
            if (!shareView.isFinishActivity&&!shareView.isStartActivity) {
                shareView.isStartActivity=YES;
                [super showProgress: progress status:status];
            }
            shareView.activityCountRequest++;
    }
    else{
      
        [super showProgress: progress status:status];
    
    }
    
}

//消失事件
- (void)dismissWithDelay:(NSTimeInterval)delay completion:(SVProgressHUDDismissCompletion)completion {

//   防止多次执行dismiss 操作
    if (self.activityCountRequest==0) {
        return;
    }
    self.activityCountRequest--;
   
    NSInteger  activityCount=self.activityCountRequest;
    if (activityCount>0||self.isFinishActivity) {
        return;
    }
    self.isFinishActivity=YES;
    self.currentDelay=delay;
    // Dismiss if visible (depending on alpha)
//   当菊花还未开启，等待菊花开启后执行closeAfterShowProgress 去关闭菊花
    if(self.alpha != 0.0f || self.hudView.alpha != 0.0f){
      [self closeShowProgressView:delay];
    }
    else{
    
        self.isWaitFinish=YES;
    }
   
}

//在开启菊花转以后，如果已经结束菊花，停止菊花转
-(void)closeAfterShowProgress{
    if (self.isWaitFinish) {
        [self  closeShowProgressView:self.currentDelay];
       
    }
   
}

-(void)closeShowProgressView:(NSTimeInterval)delay{
    
   
        // Post notification to inform user
        [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDWillDisappearNotification
                                                            object:nil
                                                          userInfo:[self notificationUserInfo]];
        
    
        // Define blocks
        __block void (^animationsBlock)(void) = ^{
            
            self.hudView.transform = CGAffineTransformScale(self.hudView.transform, 0.8f, 0.8f);
            self.alpha = 0.0f;
            self.hudView.alpha = 0.0f;
            
        };
        
        __block void (^completionBlock)(void) = ^{
            // Clean up view hierachy (overlays)
            [self.overlayView removeFromSuperview];
            [self.hudView removeFromSuperview];
            [self removeFromSuperview];
            
            // Reset progress and cancel any running animation
            self.progress = SVProgressHUDUndefinedProgress;
            [self cancelRingLayerAnimation];
            [self cancelIndefiniteAnimatedViewAnimation];
            
            // Remove observer <=> we do not have to handle orientation changes etc.
            [[NSNotificationCenter defaultCenter] removeObserver:self];
            
            // Post notification to inform user
            [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidDisappearNotification
                                                                object:self
                                                              userInfo:[self notificationUserInfo]];
            
            // Tell the rootViewController to update the StatusBar appearance
#if !defined(SV_APP_EXTENSIONS) && TARGET_OS_IOS
            UIViewController *rootController = [[UIApplication sharedApplication] keyWindow].rootViewController;
            if([rootController respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
                [rootController setNeedsStatusBarAppearanceUpdate];
            }
#endif
            // Update accesibilty
            UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);
        };
        
        if (self.fadeOutAnimationDuration > 0) {
            // Animate appearance
            [UIView animateWithDuration:self.fadeOutAnimationDuration
                                  delay:delay
                                options:(UIViewAnimationOptions) (UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseIn | UIViewAnimationOptionBeginFromCurrentState)
                             animations:^{
                                 animationsBlock();
                             } completion:^(BOOL finished) {
                                 completionBlock();
                                  NSString *currentStatus=self.statusLabel.text;
                                 [self   restartProgress:currentStatus];
                                 
                             }];
        } else {
            animationsBlock();
            completionBlock();
            NSString *currentStatus=self.statusLabel.text;
            [self   restartProgress:currentStatus];
            
        }
        
        // Inform iOS to redraw the view hierachy
        [self setNeedsDisplay];


}

-(void)restartProgress:(NSString  *)currentStatus{
    self.isFinishActivity=NO;
    self.isStartActivity=NO;
    self.isWaitFinish=NO;
//   判断是否有网络请求
    if (self.activityCountRequest&&self.undefinedProgress==SVProgressHUDUndefinedProgress) {
//        执行一次减一操作,并没有真正加载网络
        self.activityCountRequest--;
        //  如果当前开启了菊花，重新显示菊花
        [SVProgressHUDSub showProgress: SVProgressHUDUndefinedProgress status:currentStatus];
    }

}


- (void)cancelIndefiniteAnimatedViewAnimation {
    // Stop animation
    if([self.indefiniteAnimatedView respondsToSelector:@selector(stopAnimating)]) {
        [(id)self.indefiniteAnimatedView stopAnimating];
    }
    // Remove from view
    [self.indefiniteAnimatedView removeFromSuperview];
}

- (UIControl*)overlayView {
    if(!_overlayView) {
#if !defined(SV_APP_EXTENSIONS)
        CGRect windowBounds = [[[UIApplication sharedApplication] delegate] window].bounds;
        _overlayView = [[UIControl alloc] initWithFrame:windowBounds];
#else
        _overlayView = [[UIControl alloc] initWithFrame:[UIScreen mainScreen].bounds];
#endif
        _overlayView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _overlayView.backgroundColor = [UIColor clearColor];
        [_overlayView addTarget:self action:@selector(overlayViewDidReceiveTouchEvent:forEvent:) forControlEvents:UIControlEventTouchDown];
    }
    return _overlayView;
}
- (void)overlayViewDidReceiveTouchEvent:(id)sender forEvent:(UIEvent*)event {
    [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidReceiveTouchEventNotification
                                                        object:self
                                                      userInfo:[self notificationUserInfo]];
    
    UITouch *touch = event.allTouches.anyObject;
    CGPoint touchLocation = [touch locationInView:self];
    
    if(CGRectContainsPoint(self.hudView.frame, touchLocation)) {
        [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidTouchDownInsideNotification
                                                            object:self
                                                          userInfo:[self notificationUserInfo]];
    }
}

- (void)cancelRingLayerAnimation {
    // Animate value update, stop animation
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    
    [self.hudView.layer removeAllAnimations];
    self.ringView.strokeEnd = 0.0f;
    
    [CATransaction commit];
    
    // Remove from view
    [self.ringView removeFromSuperview];
    [self.backgroundRingView removeFromSuperview];
}
- (NSDictionary*)notificationUserInfo{
    return (self.statusLabel.text ? @{SVProgressHUDStatusUserInfoKey : self.statusLabel.text} : nil);
}
- (instancetype)initWithFrame:(CGRect)frame {
    if((self = [super initWithFrame:frame])) {
        _isInitializing = YES;
        
        self.userInteractionEnabled = NO;
        self.backgroundColor = [UIColor clearColor];
        
        self.foregroundColor = [UIColor blackColor];
        self.backgroundLayerColor = [UIColor colorWithWhite:0 alpha:0.4];
        
        self.alpha = 0.0f;
        //        控制次数
        self.activityCountRequest = 0;
        
//      以ios 风格展示还是以安卓风格展示
        self.progressType=PROGRESS_TYPE_ANDROID ;
    
        //背景风格，枚举类型
        self.defaultMaskType = SVProgressHUDMaskTypeClear;
        //        自定义转圈颜色
        self.defaultStyle = SVProgressHUDStyleCustom;
        [self  setBackgroundColor:[UIColor lightGrayColor]];
        
        //        菊花动画
        self.defaultAnimationType = SVProgressHUDAnimationTypeFlat;
        
        if ([UIFont respondsToSelector:@selector(preferredFontForTextStyle:)]) {
            self.font = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];
        } else {
            self.font = [UIFont systemFontOfSize:14.0f];
        }
        
        NSBundle *bundle = [NSBundle bundleForClass:[SVProgressHUD class]];
        NSURL *url = [bundle URLForResource:@"SVProgressHUD" withExtension:@"bundle"];
        NSBundle *imageBundle = [NSBundle bundleWithURL:url];
        
        UIImage* infoImage = [UIImage imageWithContentsOfFile:[imageBundle pathForResource:@"info" ofType:@"png"]];
        UIImage* successImage = [UIImage imageWithContentsOfFile:[imageBundle pathForResource:@"success" ofType:@"png"]];
        UIImage* errorImage = [UIImage imageWithContentsOfFile:[imageBundle pathForResource:@"error" ofType:@"png"]];
        
        //UIImageRenderingModeAlwaysTemplate  始终根据Tint Color绘制图片，忽略图片的颜色信息。
        
        if ([[UIImage class] instancesRespondToSelector:@selector(imageWithRenderingMode:)]) {
            self.infoImage = [infoImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            self.successImage = [successImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            self.errorImage = [errorImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        } else {
            self.infoImage = infoImage;
            self.successImage = successImage;
            self.errorImage = errorImage;
        }
        
        self.ringThickness = 4.0f;
        self.ringRadius = 18.0f;
        self.ringNoTextRadius = 24.0f;
        
        //        设置圆角直径
        self.cornerRadius = 6.0f;
        
        self.minimumDismissTimeInterval = 5.0;
        
        self.fadeInAnimationDuration = SVProgressHUDDefaultAnimationDuration;
        self.fadeOutAnimationDuration = SVProgressHUDDefaultAnimationDuration;
        
        // Accessibility support
        self.accessibilityIdentifier = @"SVProgressHUD";
        self.accessibilityLabel = @"SVProgressHUD";
        self.isAccessibilityElement = YES;
        
        _isInitializing = NO;
    
    }
    return self;
}

+(void)setSystemDevice:(BOOL)isIOS{

    SVProgressHUDSub *svprogressHUDSub=(SVProgressHUDSub  *) [SVProgressHUDSub sharedView];
    svprogressHUDSub.progressType=isIOS?PROGRESS_TYPE_IOS:PROGRESS_TYPE_ANDROID;

}

//重写  设置尺寸方法
- (void)updateHUDFrame {
    // For the beginning use default values, these
    // might get update if string is too large etc.
    CGFloat hudWidth = 100.0f;
    CGFloat hudHeight = 100.0f;
    CGFloat stringHeightBuffer = 20.0f;
    CGFloat stringAndContentHeightBuffer = 80.0f;
    CGRect labelRect = CGRectZero;
    
    // Check if an image or progress ring is displayed
    BOOL imageUsed = (self.imageView.image) && !(self.imageView.hidden);
    BOOL progressUsed = self.imageView.hidden;
    
    // Calculate size of string and update HUD size
    NSString *string = self.statusLabel.text;
    
    BOOL  isIOSOrNullText=(self.progressType==PROGRESS_TYPE_IOS)||!self.statusLabel.text.length;
    
    float  indefiniteViewInsert=10.0;
    
    float  width=isIOSOrNullText?200.0:hudViewWide-indefiniteViewWidth-indefiniteViewInsert-indefiniteViewLeftEdge;
    
    
    if(string) {
        CGSize constraintSize = CGSizeMake(width, MAXFLOAT);
        CGRect stringRect;
        if([string respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
            stringRect = [string boundingRectWithSize:constraintSize
                                              options:(NSStringDrawingOptions)(NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin)
                                           attributes:@{NSFontAttributeName: self.statusLabel.font}
                                              context:NULL];
        } else {
            CGSize stringSize;
            if([string respondsToSelector:@selector(sizeWithAttributes:)]) {
                stringSize = [string sizeWithAttributes:@{NSFontAttributeName:[UIFont fontWithName:self.statusLabel.font.fontName size:self.statusLabel.font.pointSize]}];
            } else {
#if TARGET_OS_IOS
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
                stringSize = [string sizeWithFont:self.statusLabel.font constrainedToSize:CGSizeMake(200.0f, 300.0f)];
#pragma clang diagnostic pop
#endif
            }
            stringRect = CGRectMake(0.0f, 0.0f, stringSize.width, stringSize.height);
        }
        
        CGFloat stringWidth = stringRect.size.width;
        CGFloat stringHeight = ceilf(CGRectGetHeight(stringRect));
        
        if(imageUsed || progressUsed) {
            hudHeight = stringAndContentHeightBuffer + stringHeight;
        } else {
            hudHeight = stringHeightBuffer + stringHeight;
        }
        if(stringWidth > hudWidth) {
            hudWidth = ceilf(stringWidth/2)*2;
        }
        CGFloat labelRectY = (imageUsed || progressUsed) ? 68.0f : 9.0f;
        if(hudHeight > 100.0f) {
            labelRect = CGRectMake(12.0f, labelRectY, hudWidth, stringHeight);
            hudWidth += 24.0f;
        } else {
            hudWidth += 24.0f;
            labelRect = CGRectMake(0.0f, labelRectY, hudWidth, stringHeight);
        }
    }
    
    // Update values on subviews
    
//  如果是ios的样式，或者字符串为空
    CGRect  hudViewBouns=CGRectMake(0.0f, 0.0f, MAX(self.minimumSize.width, hudWidth), MAX(self.minimumSize.height, hudHeight));
    self.cornerRadius =14.0;
    self.statusLabel.textAlignment=NSTextAlignmentCenter;
    if (!isIOSOrNullText) {
//   38  为默认两行字体的高度
        float  lableHeight=labelRect.size.height<38?38:labelRect.size.height;
//      hudView  尺寸
        hudViewBouns=CGRectMake(0.0f, 0.0f, hudViewWide,lableHeight+statusTextLableTopEdge*2);
//      标签尺寸
        labelRect=CGRectMake(indefiniteViewWidth+indefiniteViewInsert+indefiniteViewLeftEdge, statusTextLableTopEdge, labelRect.size.width, lableHeight);
        self.statusLabel.textAlignment=NSTextAlignmentLeft;
        self.cornerRadius =7.0;
    }
    
    labelRect.size.width += MAX(0, self.minimumSize.width - hudWidth);
    
    [self updateBlurBounds];
    
    
//    控制错误提示，成功提示信息图片
    self.hudView.bounds=hudViewBouns;
    if(string) {
//
        self.imageView.center =isIOSOrNullText?CGPointMake(CGRectGetWidth(self.hudView.bounds)/2, 36.0f):CGPointMake(indefiniteViewWidth/2+(indefiniteViewLeftEdge+indefiniteViewInsert)/2,hudViewBouns.size.height/2);
        
    
    } else {
       	self.imageView.center = CGPointMake(CGRectGetWidth(self.hudView.bounds)/2, CGRectGetHeight(self.hudView.bounds)/2);
    }
    
    self.statusLabel.hidden = NO;
    self.statusLabel.frame = labelRect;
    
    
    // Animate value update
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    
    if(string) {
        
        if(self.defaultAnimationType == SVProgressHUDAnimationTypeFlat) {
            SVIndefiniteAnimatedView *indefiniteAnimationView = (SVIndefiniteAnimatedView*)self.indefiniteAnimatedView;
            indefiniteAnimationView.radius = self.ringRadius;
            [indefiniteAnimationView sizeToFit];
        }
        CGPoint center = CGPointMake( isIOSOrNullText?(CGRectGetWidth(self.hudView.bounds)/2):self.indefiniteAnimatedView.frame.size.width/2+indefiniteViewLeftEdge, isIOSOrNullText?36.0f:labelRect.size.height/2+statusTextLableTopEdge);
        self.indefiniteAnimatedView.center = center;
        
        if(self.progress != SVProgressHUDUndefinedProgress) {
            self.backgroundRingView.center = self.ringView.center = CGPointMake(isIOSOrNullText?(CGRectGetWidth(self.hudView.bounds)/2):indefiniteViewWidth/2, isIOSOrNullText?36.0f:indefiniteViewWidth/2);
            
        }
        
    } else {
        if(self.defaultAnimationType == SVProgressHUDAnimationTypeFlat) {
            SVIndefiniteAnimatedView *indefiniteAnimationView = (SVIndefiniteAnimatedView*)self.indefiniteAnimatedView;
            indefiniteAnimationView.radius = self.ringNoTextRadius;
            [indefiniteAnimationView sizeToFit];
        }
        
        CGPoint center = CGPointMake(CGRectGetWidth(self.hudView.bounds)/2, CGRectGetHeight(self.hudView.bounds)/2);
        self.indefiniteAnimatedView.center = center;
        
        if(self.progress != SVProgressHUDUndefinedProgress) {
            self.backgroundRingView.center = self.ringView.center = CGPointMake((CGRectGetWidth(self.hudView.bounds)/2), CGRectGetHeight(self.hudView.bounds)/2);
        }
    }
    
    [CATransaction commit];
}

- (void)updateBlurBounds {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
    if(NSClassFromString(@"UIBlurEffect") && self.defaultStyle != SVProgressHUDStyleCustom) {
        // Remove background color, else the effect would not work
        self.hudView.backgroundColor = [UIColor clearColor];
        // Remove any old instances of UIVisualEffectViews
        for (UIView *subview in self.hudView.subviews) {
            if([subview isKindOfClass:[UIVisualEffectView class]]) {
                [subview removeFromSuperview];
            }
        }
        
        if(self.backgroundColor != [UIColor clearColor]) {
            // Create blur effect
            UIBlurEffectStyle blurEffectStyle = self.defaultStyle == SVProgressHUDStyleDark ? UIBlurEffectStyleDark : UIBlurEffectStyleLight;
            UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:blurEffectStyle];
            UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
            blurEffectView.autoresizingMask = self.hudView.autoresizingMask;
            blurEffectView.frame = self.hudView.bounds;
            
            // Add vibrancy to the blur effect to make it more vivid
            UIVibrancyEffect *vibrancyEffect = [UIVibrancyEffect effectForBlurEffect:blurEffect];
            UIVisualEffectView *vibrancyEffectView = [[UIVisualEffectView alloc] initWithEffect:vibrancyEffect];
            vibrancyEffectView.autoresizingMask = blurEffectView.autoresizingMask;
            vibrancyEffectView.bounds = blurEffectView.bounds;
            [blurEffectView.contentView addSubview:vibrancyEffectView];
            
            [self.hudView insertSubview:blurEffectView atIndex:0];
        }
    }
#endif
}

#pragma   get 方法
- (UIImageView*)imageView {
    if(!_imageView) {
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 28.0f, 28.0f)];
    }
    if(!_imageView.superview) {
        [self.hudView addSubview:_imageView];
    }
    
    return _imageView;
}
- (UILabel*)statusLabel {
    if(!_statusLabel) {
        _statusLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _statusLabel.backgroundColor = [UIColor clearColor];
        _statusLabel.adjustsFontSizeToFitWidth = YES;
        _statusLabel.textAlignment = NSTextAlignmentCenter;
        _statusLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
        _statusLabel.numberOfLines = 0;
    }
    if(!_statusLabel.superview) {
        [self.hudView addSubview:_statusLabel];
    }
    
    // Update styling  提示字体的颜色
    _statusLabel.textColor = self.foregroundColorForStyle;
    _statusLabel.font = self.font;
    
    return _statusLabel;
}
- (UIColor*)foregroundColorForStyle {
    //    设置 转圈颜色
    if(self.defaultStyle == SVProgressHUDStyleLight) {
        
        return [UIColor blackColor];
    } else if(self.defaultStyle == SVProgressHUDStyleDark) {
        return [UIColor whiteColor];
    } else {
        return self.foregroundColor;
    }
}
- (UIView*)hudView {
    if(!_hudView) {
        _hudView = [[UIView alloc] initWithFrame:CGRectZero];
        _hudView.layer.masksToBounds = YES;
        _hudView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin;
    }
    
    // Update styling
    _hudView.layer.cornerRadius = self.cornerRadius;
    _hudView.backgroundColor = self.backgroundColorForStyle;
    
    return _hudView;
}
- (UIColor*)backgroundColorForStyle {
    if(self.defaultStyle == SVProgressHUDStyleLight) {
        return [UIColor whiteColor];
    } else if(self.defaultStyle == SVProgressHUDStyleDark) {
        return [UIColor blackColor];
    } else {
        return self.backgroundColor;
    }
}
#pragma mark - Ring progress animation

- (UIView*)indefiniteAnimatedView {
    // Get the correct spinner for defaultAnimationType
    if(self.defaultAnimationType == SVProgressHUDAnimationTypeFlat){
        // Check if spinner exists and is an object of different class
        if(_indefiniteAnimatedView && ![_indefiniteAnimatedView isKindOfClass:[SVIndefiniteAnimatedView class]]){
            [_indefiniteAnimatedView removeFromSuperview];
            _indefiniteAnimatedView = nil;
        }
        
        if(!_indefiniteAnimatedView){
            _indefiniteAnimatedView = [[SVIndefiniteAnimatedView alloc] initWithFrame:CGRectZero];
        }
        
        // Update styling
        SVIndefiniteAnimatedView *indefiniteAnimatedView = (SVIndefiniteAnimatedView*)_indefiniteAnimatedView;
        indefiniteAnimatedView.strokeColor = self.foregroundColorForStyle;
        indefiniteAnimatedView.strokeThickness = self.ringThickness;
        //      有字的时候为小圈，没字的时候为大全
        indefiniteAnimatedView.radius = self.statusLabel.text ? self.ringRadius : self.ringNoTextRadius;
        
    } else {
        // Check if spinner exists and is an object of different class
        if(_indefiniteAnimatedView && ![_indefiniteAnimatedView isKindOfClass:[UIActivityIndicatorView class]]){
            [_indefiniteAnimatedView removeFromSuperview];
            _indefiniteAnimatedView = nil;
        }
        
        if(!_indefiniteAnimatedView){
            _indefiniteAnimatedView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        }
        
        // Update styling  菊花转颜色
        UIActivityIndicatorView *activityIndicatorView = (UIActivityIndicatorView*)_indefiniteAnimatedView;
        activityIndicatorView.color = self.foregroundColorForStyle;
    }
    [_indefiniteAnimatedView sizeToFit];
    
    return _indefiniteAnimatedView;
}
- (SVProgressAnimatedView*)ringView {
    if(!_ringView) {
        _ringView = [[SVProgressAnimatedView alloc] initWithFrame:CGRectZero];
    }
    
    // Update styling
    _ringView.strokeColor = self.foregroundColorForStyle;
    _ringView.strokeThickness = self.ringThickness;
    _ringView.radius = self.statusLabel.text ? self.ringRadius : self.ringNoTextRadius;
    
    return _ringView;
}
- (SVProgressAnimatedView*)backgroundRingView {
    if(!_backgroundRingView) {
        _backgroundRingView = [[SVProgressAnimatedView alloc] initWithFrame:CGRectZero];
        _backgroundRingView.strokeEnd = 1.0f;
    }
    
    // Update styling
    _backgroundRingView.strokeColor = [self.foregroundColorForStyle colorWithAlphaComponent:0.1f];
    _backgroundRingView.strokeThickness = self.ringThickness;
    _backgroundRingView.radius = self.statusLabel.text ? self.ringRadius : self.ringNoTextRadius;
    
    return _backgroundRingView;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
